#!/usr/bin/env python
# -*- coding: utf-8 -*

import gst
import os
from urllib import urlopen
from box import LBox
from clutter import Label
import alwaysontop

class WebRadiosDisplayer(LBox):
    def __init__(self):
        LBox.__init__(self)
        self.radios = WebRadios()
        self.player = WebRadioPlayer()
        self.build_list()
        self._build_background()

    def build_list(self):
        for radio in self.radios:
            self.add_button(radio)

    def add_button(self, radio):
        r = RadioButton(radio, self.play_radio)
        self.add(r)

    def play_radio(self, source, event, radio):
        self.player.play_radio(radio)

class RadioButton(Label):
    def __init__(self, radio, callback):
        Label.__init__(self)
        self.set_text(radio["name"])
        self.set_font_name(alwaysontop.font_name)
        self.set_color(alwaysontop.font_color)
        self.set_reactive(True)
        self.connect("button-press-event", callback, radio)
        self.show()

class WebRadios(list):
    def __init__(self):
        list.__init__(self)
        self.add_webradio("iwayhigh", "http://iwayhigh.net:8000/listen.pls")
        self.add_webradio("fip", "http://www.tv-radio.com/station/fip_mp3/fip_mp3-128k.m3u")
        self.add_webradio("deepmix", "http://deepmix.ru/deepmix128.pls")
        self.add_webradio("nova", "http://www.novaplanet.com/radio-nova/player2/radionova.pls.php")

    def add_webradio(self, name, url):
        self.append({"name": name, "url": url})

    def get_webradio_of_name(self, name):
        for radio in self:
            if radio["name"] == name:
                return radio

class WebRadioPlayer(object):

    def play_radio(self, wradio):
        self.stream_urls = list()
        m3u_file = urlopen(wradio["url"])
        data = m3u_file.readlines()
        for line in data:
            if line.startswith("#"):
                pass
            else:
                if line.find("http://") != -1:
                    self.stream_urls.append(line.split("http://")[1])
        if len(self.stream_urls) != 0:
            pipeline_desc = "souphttpsrc location=http://%s ! queue2 ! mad ! queue ! alsasink" %self.stream_urls[0]
            if hasattr(self, "pipeline"):
                if self.pipeline.get_state()[1].value_name == "GST_STATE_PLAYING":
                    self.pipeline.set_state(gst.STATE_NULL)
            self.pipeline = p = gst.parse_launch(pipeline_desc)
            p.set_state(gst.STATE_PLAYING)

if __name__ == "__main__":
    wr = WebRadios()
    wp = WebRadioPlayer()
    
    wp.play_radio(wr.get_webradio_of_name("deepmix"))
    #wp.play_radio(wr.get_webradio_of_name("iwayhigh"))

    import gtk
    gtk.main()
